package com.asas.spaceflight.controller;

import java.util.Iterator;

import com.asas.spaceflight.model.PhysicalEntity;
import com.asas.spaceflight.model.World;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;

public class PhysicalController {
	
	private World world;
	private float meterToPixel;
	
	private Array<PhysicalEntity> entities = new Array<PhysicalEntity>();

	public PhysicalController(World world) {
		this.world			= world;
		this.meterToPixel	= 21;
	}
	
	public void update(float delta) {
		Iterator<PhysicalEntity> iterator = getEntities().iterator();
		while (iterator.hasNext()) {
			updateEntity(iterator.next(), delta);
		}
	}
	
	private void updateEntity(PhysicalEntity entity, float delta) {
		Vector2 velocity = entity.getVelocity();

		// Update position
		float meterToPixelD = meterToPixel * delta;
		entity.getPosition().add(velocity.x * meterToPixelD, velocity.y * meterToPixelD);
		
		// Update vertical velocity
		velocity.y = velocity.y + world.getGravity() * delta;
		
		// Update horizontal velocity
		if (velocity.x < 0) {
			velocity.x += world.getFriction() * delta;
			if (velocity.x > 0) {
				velocity.x = 0;
			}				
		}
		else if (velocity.x > 0) {
			velocity.x -= world.getFriction() * delta;
			if (velocity.x < 0) {
				velocity.x = 0;
			}
		}
		
		//TODO: Update angle

		/*/ DEBUG		
		System.out.println("time: " + System.currentTimeMillis() + " | "
				+ "velocity: " + velocity + " | "
				+ "position: " + entity.getPosition() + " | "
				+ "angle: " + entity.getAngle() + " | "
				+ "delta: " + delta);
		//*/
	}

	public Array<PhysicalEntity> getEntities() {
		return entities;
	}
	
}
